import axios from '../../utils/axios'
const app = getApp();
Page({
  data: {
    goodsList: [],
    searchVal: '',
    col1: [],
    col2: [],
  },
  onLoad: async function (options) {
    await this.getGoods();
    this.getBanner();
  },
  onReady: function () { },
  onShow: function () {
    // 判断登录
    if (app.globalData.userInfo.length === 0) {
      wx.switchTab({
        url: '/pages/user/user',
      });
    }
  },
  onHide: function () {

  },
  onUnload: function () {
    // 解绑
    if (this._observer)
      this._observer.disconnect()
  },
  onPullDownRefresh: async function () {
    wx.showLoading({
      title: 'loading',
    });
    await this.getGoods();
    wx.hideLoading();
    wx.stopPullDownRefresh();
  },
  onReachBottom: function () { },
  onShareAppMessage: function () { },
  // 获取商品列表
  async getGoods() {
    let res = await axios({
      url: '/api/mall/product',
      data: {
        page: this.data.goodsList.length / 4,
        size: 4,
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    // let a = res.data.content.filter(item => item.isDel != '1');
    // console.log('tempA!!!!!!!!!!!!!!!!!!!!!!', a);
    res.data.content = res.data.content.filter(item => item.isDel != '1')
    // return;
    // 复制数组
    let goodsList = this.data.goodsList.concat();
    // 添加json数据
    goodsList = goodsList.concat(res.data.content);
    // 数组对象去重 *标记，没看懂
    var hash = {};
    goodsList = goodsList.reduce((item, next) => {
      hash[next.id] ? '' : hash[next.id] = true && item.push(next);
      return item
    }, []);
    // 分栏
    let col1 = [];
    let col2 = [];
    goodsList.forEach(item => col1.length <= col2.length ? col1.push(item) : col2.push(item));
    // 赋值
    this.setData({
      goodsList,
      col1,
      col2,
    });
    // 监听下拉刷新
    if (goodsList.length == this.data.goodsList.length)
      if (this._observer)
        this._observer.disconnect()
      else
        this.initObserver
  },
  async navigationTo(e) {
    console.log('handle click', e);
    let detailData = e.currentTarget.dataset.detaildata;
    if (e.currentTarget.dataset.bannerurl) {
      let id = JSON.parse(e.currentTarget.dataset.bannerurl).id;
      let res = await axios({
        url: '/api/mall/product',
        data: {
          id
        }
      })
      detailData = res.data.content[0]
    };
    wx.navigateTo({
      url: './detail/goods/goods',
      success: (res) => {
        // 发送数据        
        res.eventChannel.emit('sendDetailData', {
          data: detailData
        })
      },
    });
  },
  async getBanner() {
    let bannerRes = await axios({
      url: '/api/shop/home/banner',
    })
    console.log('bannerRes', bannerRes);
    this.setData({
      banner: bannerRes.data.content
    })
  },
  async search(e) {
    let res = await axios({
      url: '/api/mall/product',
      data: {
        storeName: e.currentTarget.dataset.searchkey || this.data.searchVal
      }
    })
    let searchList = res.data.content;
    wx.navigateTo({
      url: './detail/search/search',
      success: (res) => {
        // 发送数据        
        res.eventChannel.emit('sendsearchListData', {
          data: searchList
        })
      },
      fail: err => console.log(err)
    });

  },
  searchValUpData(e) {
    this.setData({
      searchVal: e.detail
    })
  },
  // observer
  // 监听元素进入视窗
  async initObserver() {
    // 解绑
    if (this._observer)
      this._observer.disconnect()
    this._observer = wx.createIntersectionObserver(this, {
      // 阈值设置少，避免触发过于频繁导致性能问题
      thresholds: [0, 1],
      // 监听多个对象
      // observeAll: true
    })
    this._observer
      .relativeToViewport({
        bottom: 200
      })
      .observe('.lastBlock', (res) => {
        console.log(res);
        if (res.intersectionRatio == 1) {
          this.getGoods();
        }
      })
  },
})